import urllib.request


def load_baidu():
    url = "https://www.baidu.com"


    header = {
        # 浏览器的版本
        # "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"
    }

    # 创建请求对象
    request = urllib.request.Request(url, headers = header)

    # 动态去添加header的信息
    request.add_header("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36")

    # 请求网络数据 (不再此处增加请求头的信息)
    response = urllib.request.urlopen(request)
    # 响应头
    # print(response.headers)

    data = response.read().decode("utf-8")


    # 获取完整的url
    full_url = request.get_full_url()
    print(full_url)

    # 获取请求头的信息
    request_header = request.headers
    # print(request_header)

    # 第二种方式打印headers的信息   s首字母需要大写,其他的字母必须小写
    UserAgentStr = request.get_header("User-agent")
    # print(UserAgentStr)


    with open("02header.html", "w", encoding="utf-8") as f:
        f.write(data)




load_baidu()